<template>
	<view class="chatContext">
		<view class="fastReplyBox" v-if="visitorProfile">
			<uni-table emptyText="暂无更多数据" >
				<uni-tr>
					<uni-th  width="80">访客名</uni-th>	
					<uni-th >{{visitor_name}}</uni-th>
				</uni-tr>
				<uni-tr align="left" :key="item.key" v-for="item in visitorExtra">
					<uni-td>{{item.key}}</uni-td>
					<uni-td>{{item.val}}
						<a style="margin: 0 10px;color: #07a9fe;" v-if="item.key=='同IP访客'" type="default" v-on:click="goTo('/pages/index/history?client_ip='+visitor_ip)">查询</a>
					</uni-td>
				</uni-tr>
			</uni-table>
			<button style="margin: 10px;" size="mini" type="default" v-on:click="visitorProfile=false">关闭</button>
		</view>
		

		
		<view class="flyNotice" v-if="messages.length==0">
			<view><image style="width: 135px;height: 132px;" src="@/static/images/no-chat.png"></image></view>
			<view style="color: #333;">暂无消息记录</view>
			<view>没有要处理的对话，休息一下吧</view>
		</view>

		<view class="chatTime" v-on:click="getMessages" v-show="showLoadMore">{{moremessage}}</view>
		<view class="chatBox"  v-on:click="showFaceIcon=false">
			<view v-for="(v,index) in messages" v-bind:class="{'chatBoxMe': v.mes_type=='kefu'}" :key="v.msg_id">
				<view class="chatTime" v-bind:class="{'chatTimeHide': v.show_time==false}">{{formatTime(v.time)}}</view>
				<view class="chatLittle">
					<image class="flyAvatar" :src="v.avator"></image>
				</view>
				<view class="chatBig">
					<view class="chatUser">{{v.name}}</view>
					<view class="chatContent"  >
						<mp-html :content="v.content" :selectable="true"/>
						<view style="color: #07a9fe;" v-show="v.mes_type!='kefu'"  @click="translate(index,v.content)">翻译</view>
					</view>
					<view class="chatReadStatus" v-show="v.mes_type=='kefu'">{{v.read_status}}</view>
					<view class="deleteMessage" v-show="v.mes_type=='kefu'"  @click="longDelete(v.msg_id)">撤回</view>
				</view>
				<view class="clear"></view>
			</view>
		</view>
		<view class="fastReplyBox" v-if="remark">
			<view class="remarkDialog">
				<uni-forms>
					<uni-easyinput class="mt-10" type="text" v-model="realName"  placeholder="姓名" />
					<uni-easyinput class="mt-10" type="text"  v-model="tel"  placeholder="手机" />
					<uni-easyinput class="mt-10" type="text"  v-model="wechat"  placeholder="微信" />
					<uni-easyinput class="mt-10" type="text"  v-model="qq"  placeholder="QQ" />
					<uni-easyinput class="mt-10" type="text"  v-model="email"  placeholder="邮箱" />
					<uni-easyinput class="mt-10" type="textarea"  v-model="comment"  placeholder="备注"/>
				</uni-forms>
				<button type="primary" @click="saveRemark" class="mt-10">保存</button>
				<view class="mt-10">
					<uni-tag :key="visitorTag.id" @click="delTag(visitorTag.tag_name)" class="mr-10 mt-10" type="primary" :text="visitorTag.tag_name" v-for="visitorTag in visitorTags"></uni-tag>
					<uni-data-picker class="mt-10" :localdata="entTags" popup-title="请选择标签" @change="changeTag"></uni-data-picker>
					<uni-easyinput class="mt-10" type="text"  v-model="tagName"  placeholder="新标签" @blur="doChangeTag(tagName)"/>
				</view>
				<button @click="closeRemark" class="mt-10">关闭</button>
				<button type="warn" @click="blackVisitor('visitor')" class="mt-10">拉黑访客</button>
				<button type="warn" @click="blackVisitor('ip')" class="mt-10">拉黑IP</button>
			</view>
		</view>

		<view class="fastReplyBox" v-if="recorderBtn">
			<view class="recorderBox">
				<audio :src='recorder.localUrl' v-if='recorder' author="客服助手" name='本地录音' controls="true" style="margin:0 auto;"></audio>
				<button class="recorderBtn" @tap="startRecord" type="primary">开始录音</button>
				<button class="recorderBtn" @tap="endRecord" type="primary" v-show="endRecorderBtn">停止录音</button>
				<button class="recorderBtn" @tap="sendRecord" type="primary" v-show="sendRecorderBtn">发送录音</button>
				<button class="recorderBtn" v-on:click="recorderBtn=false" type="warn">关闭</button>
				<!-- #ifdef  H5 -->
				<mumu-recorder ref='recorder' @success='handlerRecordSuccess' @error='handlerRecordError'></mumu-recorder>
				<!-- #endif -->
			</view>
		</view>
		<view class="fastReplyBox remoteVideoMask" style="display: none;" v-show="peerjs.remoteVideoStream!=null">
			<video id="remoteVideo" controls="true" autoplay="true" style="width: 100%;height: 100%;"></video>
			<view class="refuse" v-on:click="callClear">挂断</view>
		</view>
		<view class="fastReplyBox remoteVideoMask" style="display: none;" v-show="peerjs.remoteAudioStream!=null">
			<image class="remoteVideoMaskLogo" :src="kefuInfo.avator"></image>
			<audio id="remoteAudio" controls="true" autoplay="true"  style="display:none"></audio>
			<view class="refuse" v-on:click="callClear">挂断</view>
		</view>
		<view class="fastReplyBox" v-if="fastReplyBtn && replys.length!=0">
			<view style="padding: 10px;">
				<input style="padding: 5px 0;" class="searchArea" placeholder="搜索快捷回复" v-model="searchReplyItem" @input="searchReply" />
			</view>
			
			<uni-collapse accordion>
				<uni-collapse-item :title="reply.group_name" :key="reply.group_id" v-for="reply in replys" @click="messageContent=replyItem.item_content;fastReplyBtn=false">
					<view  class="replyBox"  v-for="replyItem in reply.items" :key="reply.item_id"  @click="messageContent=replyItem.item_content;fastReplyBtn=false">
						<view class="replyTitle">{{replyItem.item_name}}</view>
						<view   class="replyContent"><mp-html :preview-img="false" :content="replaceContent(replyItem.item_content)" /></view>
					</view>
				</uni-collapse-item>
			</uni-collapse>
			<button style="margin: 10px;" size="mini" type="default" v-on:click="fastReplyBtn=false">关闭</button>
		</view>
		
		<view class="fastReplyBox" v-if="otherKefuBtn && otherKefuList.length!=0">
			<uni-table emptyText="暂无更多数据">
				    <uni-tr>
				        <uni-th >账号</uni-th>	
				        <uni-th >操作</uni-th>
				    </uni-tr>
				<uni-tr align="left" :key="item.name"  v-for="item in otherKefuList">
					<uni-td>{{item.nickname}} ( {{item.name}} )</uni-td>
					<uni-td>
						<span v-show="item.status=='offline'">{{item.status}}</span>
						<button @click="transKefuVisitor(item.name,visitor_id)" v-show="item.status=='online'" size="mini" type="primary" v-on:click="otherKefuBtn=false">转接</button>
					</uni-td>
				</uni-tr>
			</uni-table>
			<button style="margin: 10px;" size="mini" type="default" v-on:click="otherKefuBtn=false">关闭</button>
		</view>
		
		
		<view class="chatBoxSend">
			<view class="inputing" v-show="inputingAction!=''">{{inputingAction}}</view>
			<view class="topBtns">
				<button class="txtBtn"  size="mini" type="default" v-on:click="visitorProfile==true? visitorProfile=false : visitorProfile=true">访客资料</button>
				<button class="txtBtn" size="mini" type="default" v-on:click="openFastReply()">快捷回复</button>
				<button class="txtBtn" size="mini" type="default" v-on:click="openRemark()">备注</button>
				<switch @change="switchRobotStatus" :checked="robotStatus" style="transform:scale(0.7)"/>
			</view>
			<view class="faceBox" v-if="showFaceIcon">
				<div class="emojis">
					<span v-for="key in emojis" @click="messageContent+=key;showFaceIcon=false">{{key}}</span>
				</div>
			</view>
			<view>

				<view class="chatBoxSendIcons">
					<uni-icons class="mr-10" v-on:click="showFaceIcon==true?showFaceIcon=false:showFaceIcon=true" custom-prefix="iconfont" type="icon-xiaolian" size="22" color="#8b8b8b"></uni-icons>
					<uni-icons class="mr-10" v-on:click="uploadImage" type="image" size="28" color="#8b8b8b"></uni-icons>
					<uni-icons class="mr-10" v-on:click="uploadFile" type="upload-filled" size="26" color="#8b8b8b"></uni-icons>
					<uni-icons class="mr-10" v-on:click="recorderBtn=true" type="mic" size="26" color="#8b8b8b"></uni-icons>
					<uni-icons class="mr-10" v-on:click="translateKefu" type="font" size="26" color="#8b8b8b"></uni-icons>
					<uni-icons class="mr-10" v-on:click="transferKefu" type="redo" size="26" color="#8b8b8b"></uni-icons>
					<uni-icons class="mr-10" v-on:click="sendComment" type="star-filled" size="28" color="#8b8b8b"></uni-icons>
					<!-- #ifdef  H5 -->
					<uni-icons class="mr-10" v-on:click="callPhone" type="phone" size="25" color="#8b8b8b"></uni-icons>
					<uni-icons class="mr-10" v-on:click="callVideo" type="videocam" size="28" color="#8b8b8b"></uni-icons>
					<!-- #endif -->
				</view>
				<button  class="btnArea" v-on:click="chatToUser" type="primary" size="mini">发送</button>
			</view>
			<textarea  :adjust-position="true" maxlength="-1" class="chatArea" v-on:click="readMessages();pageScrollToBottom(true)" v-model="messageContent"  placeholder="请输入信息"></textarea>
		</view>
	</view>

</template>

<script>
	import toolsHelper from '../../common/tools.js';
	import WebSocketClass from '../../common/socket.js'
	import MumuRecorder from '@/uni_modules/mumu-recorder/components/mumu-recorder/mumu-recorder.vue'

	// #ifdef  H5
	import "../../common/peer.js"
	// #endif
	const app = getApp()
	
	export default {
		components: {MumuRecorder },
		data() {
			return {
				baseUrl: getApp().globalData.baseUrl,
				wsBaseUrl: getApp().globalData.wsBaseUrl,
				kefuInfo:{
					avator:"",
					nickname:"",
					username:""
				},
				messages: [],
				messageContent: "",
				sendDisabled: false,
				token: "",
				visitor:{},
				visitor_id: "",
				visitorExtra:[],
				visitor_name: "",
				visitor_ip:"",
				isDisabled: false,
				area: "",
				showArea: false,
				scrollSize: 2,
				showFaceIcon:false,
				face:[],
				faceTitles : ["[a]", "[b]", "[c]", "[d]", "[e]", "[f]", "[g]", "[h]", "[i]", "[j]", "[k]", "[l]", "[m]", "[n]", "[o]", "[p]", "[q]", "[r]", "[s]", "[t]", "[u]", "[v]", "[w]", "[x]", "[y]", "[z]", "[aa]", "[bb]", "[cc]", "[dd]", "[ee]", "[ff]", "[gg]", "[hh]", "[ii]", "[jj]", "[kk]", "[ll]", "[mm]", "[nn]", "[oo]", "[pp]", "[qq]", "[rr]", "[ss]", "[tt]", "[uu]", "[vv]", "[ww]", "[xx]", "[yy]", "[zz]", "[a1]", "[b1]", "[good]", "[NO]", "[c1]", "[d1]", "[e1]", "[f1]", "[g1]", "[h1]", "[i1]", "[g1]", "[k1]", "[l1]", "[m1]", "[n1]", "[o1]", "[p1]", "[q1]", "[cake]"],
				noticeContent:"通知: 无",
				currentPage:1,
				loadMoreDisable:false,
				showLoadMore:false,
				inputingAction:"",
				moremessage:"点击加载更多记录",
				showRecorder:false,
				recorder: null,
				realName:"",
				tel:"",
				wechat:"",
				qq:"",
				email:"",
				comment:"",
				replys:[],
				visitorTags:[],
				entTags:[],
				tagName:"",
				messageExist:[],
				Loop:null,
				voicePath: '',
				visitorProfile:false,
				fastReplyBtn:false,
				recorderBtn:false,
				otherKefuBtn:false,
				endRecorderBtn:true,
				sendRecorderBtn:false,
				remark:false,
				otherKefuList:[],
				robotStatus:true,
				peerjs:{
					peer:null,
					peerjsId:"",
					localStream:null,
					remoteAudioStream:null,
					remoteVideoStream:null,
					call:null,
					visitorId:"",
					callCancel:false,
				},
				searchReplyItem:"",
				emojis:{"smile":"😄","smiley":"😃","grinning":"😀","blush":"😊","wink":"😉","heart_eyes":"😍","kissing_heart":"😘","kissing_closed_eyes":"😚","kissing":"😗","kissing_smiling_eyes":"😙","stuck_out_tongue_winking_eye":"😜","stuck_out_tongue_closed_eyes":"😝","stuck_out_tongue":"😛","flushed":"😳","grin":"😁","pensive":"😔","relieved":"😌","unamused":"😒","disappointed":"😞","persevere":"😣","cry":"😢","joy":"😂","sob":"😭","sleepy":"😪","disappointed_relieved":"😥","cold_sweat":"😰","sweat_smile":"😅","sweat":"😓","weary":"😩","tired_face":"😫","fearful":"😨","scream":"😱","angry":"😠","rage":"😡","triumph":"😤","confounded":"😖","laughing":"😆","yum":"😋","mask":"😷","sunglasses":"😎","sleeping":"😴","dizzy_face":"😵","astonished":"😲","worried":"😟","frowning":"😦","anguished":"😧","imp":"👿","open_mouth":"😮","grimacing":"😬","neutral_face":"😐","confused":"😕","hushed":"😯","smirk":"😏","expressionless":"😑","man_with_gua_pi_mao":"👲","man_with_turban":"👳","cop":"👮","construction_worker":"👷","guardsman":"💂","baby":"👶","boy":"👦","girl":"👧","man":"👨","woman":"👩","older_man":"👴","older_woman":"👵","person_with_blond_hair":"👱","angel":"👼","princess":"👸","smiley_cat":"😺","smile_cat":"😸","heart_eyes_cat":"😻","kissing_cat":"😽","smirk_cat":"😼","scream_cat":"🙀","crying_cat_face":"😿","joy_cat":"😹","pouting_cat":"😾","japanese_ogre":"👹","japanese_goblin":"👺","see_no_evil":"🙈","hear_no_evil":"🙉","speak_no_evil":"🙊","skull":"💀","alien":"👽","hankey":"💩","fire":"🔥","sparkles":"✨","star2":"🌟","dizzy":"💫","boom":"💥","anger":"💢","sweat_drops":"💦","droplet":"💧","zzz":"💤","dash":"💨","ear":"👂","eyes":"👀","nose":"👃","tongue":"👅","lips":"👄","thumbs_up":"👍","-1":"👎","ok_hand":"👌","facepunch":"👊","fist":"✊","wave":"👋","hand":"✋","open_hands":"👐","point_up_2":"👆","point_down":"👇","point_right":"👉","point_left":"👈","raised_hands":"🙌","pray":"🙏","clap":"👏","muscle":"💪","walking":"🚶","runner":"🏃","dancer":"💃","couple":"👫","family":"👪","couplekiss":"💏","couple_with_heart":"💑","dancers":"👯","ok_woman":"🙆","no_good":"🙅","information_desk_person":"💁","raising_hand":"🙋","massage":"💆","haircut":"💇","nail_care":"💅","bride_with_veil":"👰","person_with_pouting_face":"🙎","person_frowning":"🙍","bow":"🙇","tophat":"🎩","crown":"👑","womans_hat":"👒","athletic_shoe":"👟","mans_shoe":"👞","sandal":"👡","high_heel":"👠","boot":"👢","shirt":"👕","necktie":"👔","womans_clothes":"👚","dress":"👗","running_shirt_with_sash":"🎽","jeans":"👖","kimono":"👘","bikini":"👙","briefcase":"💼","handbag":"👜","pouch":"👝","purse":"👛","eyeglasses":"👓","ribbon":"🎀","closed_umbrella":"🌂","lipstick":"💄","yellow_heart":"💛","blue_heart":"💙","purple_heart":"💜","green_heart":"💚","broken_heart":"💔","heartpulse":"💗","heartbeat":"💓","two_hearts":"💕","sparkling_heart":"💖","revolving_hearts":"💞","cupid":"💘","love_letter":"💌","kiss":"💋","ring":"💍","gem":"💎","bust_in_silhouette":"👤","speech_balloon":"💬","footprints":"👣"},
			}
		},
		// 页面显示
		onLoad(options) {
			var res = uni.getStorageSync('app');
			if (res) {
				this.token = res.token;
			}
			let domainInfo = uni.getStorageSync('domain');
			if (domainInfo) {
				this.baseUrl = domainInfo.domain;
				this.wsBaseUrl=toolsHelper.getWsUrl(domainInfo.domain);
			}
			
			this.visitor_id = options.visitor_id;

			this.getKefuInfo();
			this.getVisitor();
			this.currentPage=1;
			this.messages=[];
			this.getMessages();

		},
		onShow() {
			this.checkAuth();
			var temp=this.currentPage;
			this.currentPage=1;
			this.getMessages();
			this.currentPage=temp;
			this.readMessages();
			this.initSocket();
			this.getFaces();
		},
		methods: {
			initSocket(){

				      // 如果已经有sockt实例
				      if (app.globalData.socketObj) {
				        // 如果sockt实例未连接
				        if (!app.globalData.socketObj.isConnect) {
				          app.globalData.socketObj.initSocket()
				        }
				      } else {
				        app.globalData.socketObj = new WebSocketClass(
				          this.wsBaseUrl + "?token=" + this.token,
				          60
				        )
				        app.globalData.socketObj.initSocket()
				      }
			},

			getVisitor() {
				var baseUrl = this.baseUrl;
				var _this = this;
				uni.request({
					url: baseUrl + '/kefu/visitor?visitorId=' + this.visitor_id + '&token=' + _this.token,
					method: 'GET',
					success: function(res) {
						var code = res.data.code;
						if (code == 200) {
							_this.visitor_name = res.data.result.name;
							_this.visitor_ip = res.data.result.client_ip;
							uni.setNavigationBarTitle({
								title: _this.visitor_name
							});
							var temp={key:'标题',val:res.data.result.refer}
							_this.visitorExtra.push(temp);
							_this.visitorExtra.push({key:'IP地址',val:res.data.result.client_ip});
							_this.visitorExtra.push({key:'城市',val:res.data.result.city});
							_this.visitorExtra.push({key:'操作系统',val:res.data.os_version});
							_this.visitorExtra.push({key:'浏览器',val:res.data.browser});
							_this.visitorExtra.push({key:'首次访问',val:res.data.create_time});
							_this.visitorExtra.push({key:'上次访问',val:res.data.last_time});
							_this.visitorExtra.push({key:'访问次数',val:res.data.result.visit_num});
							_this.visitorExtra.push({key:'同IP访客',val:res.data.same_ip});
							_this.visitorExtra.push({key:'访客ID',val:_this.visitor_id});
							//访客状态位,第一位是否开启机器人回复
							_this.robotStatus=res.data.result.state.substr(0,1)=="2"?false:true;
							_this.visitor=res.data.result;
							if(res.data.result.extra && res.data.result.extra!=""){
								let baseStr=res.data.result.extra.replace(" ","+");
								var s3=toolsHelper.b64DecodeUnicode(baseStr);

								var extra=JSON.parse(s3);console.log(extra);
								if (typeof extra=="string"){
									extra=JSON.parse(extra);
								}
								for(var key in extra){
									if(extra[key]==""){
										extra[key]="无";
									}
									if(key=="visitorAvatar"||key=="visitorName"||key=="visitorProduct") continue;
									var temp={key:key,val:extra[key]}
									_this.visitorExtra.push(temp);
								}
							}
						}
					}
				});
			},
			readMessages(){
				uni.request({
					url: this.baseUrl + '/kefu/messages_read?token='+this.token,
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					data:{
						visitor_id:this.visitor_id,
					},
					success: function(res) {
					}
				});
			},
			getMessages() {
				var _this=this;
				var pagesize=10;
				// if(_this.currentPage<=1){
				// 	pagesize=5;
				// }
				if(_this.loadMoreDisable){
					return;
				}
				uni.showLoading({
					title: "加载中..."
				});

				this.moremessage="加载中";
				this.loadMoreDisable=true;
				uni.request({
					url: this.baseUrl + '/kefu/messages_page' ,
					method: 'GET',
					data:{
						pagesize:pagesize,
						page:_this.currentPage,
						visitor_id:_this.visitor_id,
						token:_this.token,
					},
					success: function(res) {
						uni.hideLoading();
						var messages = res.data.result.list;
						var len=messages.length;
						if(len<=0){
							_this.showLoadMore=false;
							return;
						}else if(len<pagesize){
							_this.showLoadMore=false;
						}else{
							_this.showLoadMore=true;
						}
						
						for (var i in messages) {
							var item=messages[i];
							var visitorMes=[];
							visitorMes = messages[i];
							visitorMes.avator=toolsHelper.getImageUrl(visitorMes.avator,_this.baseUrl);
							visitorMes.content = _this.replaceContent(visitorMes["content"], _this.baseUrl);
							if(!_this.messageExist["id_"+visitorMes.msg_id]){
								_this.messages.unshift(visitorMes);
								_this.messageExist["id_"+visitorMes.msg_id]=1;
							}
							if (visitorMes.read_status== "read") {
								visitorMes.read_status = "已读";
							} else {
								visitorMes.read_status = "未读";
							}
						}
						
		
						if(_this.currentPage<=1){
							//setTimeout(function() {
								_this.pageScrollToBottom(true);
							//}, 1000);
						}
						_this.currentPage++;
						_this.moremessage="点击加载更多记录";
						_this.loadMoreDisable=false;
					}
				});
			},
			checkAuth() {
				var _this = this;
				uni.request({
					url: _this.baseUrl + '/uc/v1/refreshToken?token=' + _this.token,
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: function(res) {
						var code = res.data.code;
						if (code != 20000) {
							uni.navigateTo({
								url: '/pages/index/login'
							});
						} else {
							uni.setStorageSync("app", {
								token: res.data.result.token,
							});
							_this.onlineIntime();
						}
					}
				});
			},
			getKefuInfo() {
				var _this = this;
				uni.request({
					url: _this.baseUrl + '/kefu/kefuinfo?token=' + _this.token,
					method: 'GET',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: function(res) {
						var code = res.data.code;
						var result = res.data.result;
						_this.kefuInfo.avator=result.avator;
						_this.kefuInfo.username=result.name;
						_this.kefuInfo.nickname=result.nickname;
					}
				});
			},
			//用户实时上下线
			onlineIntime() {
				let _this = this;
				var timer = null;
				console.log(this.wsBaseUrl + "?token=" + this.token);
				// uni.connectSocket({
				// 	url: this.wsBaseUrl + "?token=" + this.token,
				// });
				// uni.onSocketClose((res) => {
				// });
				// uni.onSocketOpen((res) => {
				// 	let _this = this;
				// 	let mes = {}
				// 	mes.type = "ping";
				// 	mes.data = "";
				// 	timer = setInterval(function() {
				// 		uni.sendSocketMessage({
				// 			data: JSON.stringify(mes),
				// 		});
				// 	}, 5000)
				// });
				uni.onSocketMessage((res) => {
				//uni.$on('message',(res) => {
					var redata = JSON.parse(res.data);
					switch (redata.type) {
						case "message":
							_this.recvMessage(redata.data);
							break;
						case "inputing":
							if (redata.data.from != _this.visitor_id) {
								return;
							}
							if (redata.data.content != "") {
								_this.inputingAction="正在输入:"+redata.data.content
							}else{
								_this.inputingAction="";
							}
							uni.setNavigationBarTitle({
								title: "[在线]:" + _this.visitor_name
							});

							break;
						case "read":
							if (redata.data.visitor_id == _this.visitor_id) {
								for(var i=0;i<this.messages.length;i++){
									this.$set(this.messages[i],'read_status',"已读");
								}
							}
							break;
						case "userOffline":
							_this.showNoticeBar(redata.data.name + "离线");
							if (redata.data.visitor_id != _this.visitor_id) {
								return;
							}
							uni.setNavigationBarTitle({
								title: "[离线]:" + _this.visitor_name
							});
							break;
						case "userOnline":
							toolsHelper.playVoice();
							_this.showNoticeBar(redata.data.username + "来了");
							if (redata.data.visitor_id != _this.visitor_id) {
								return;
							}
							uni.setNavigationBarTitle({
								title: "[在线]:" + _this.visitor_name
							});
							break;
						case "callCancel":
							_this.callClear();
							break;
						case "callpeer":
								if(_this.peerjs.visitorId){
									uni.request({
										url: _this.baseUrl + '/kefu/callVisitor?token='+_this.token,
										method: 'POST',
										data: {
											peer_id:"222",
											visitor_id:redata.data.visitor_id,
											action:"refuse"
										}
									});
									return;
								}
								//通话请求
								uni.showModal({
									title: '提示',
									content: redata.data.name+'请求通话？',
									cancelText: "拒绝", // 取消按钮的文字  
									confirmText: "接通", // 确认按钮的文字  
									showCancel: true, // 是否显示取消按钮，默认为 true
									confirmColor: '#39B54A',
									cancelColor: '#f55850',
									success: (res) => {
										if(res.confirm) {  
											console.log('comfirm') //点击确定之后执行的代码
											_this.initPeerjs(redata.data.visitor_id);
										} else {  
											uni.request({
												url: _this.baseUrl + '/kefu/callVisitor?token='+_this.token,
												method: 'POST',
												data: {
													peer_id:"222",
													visitor_id:redata.data.visitor_id,
													action:"refuse"
												}
											});
										} 
									}
								})
							break;
					}
				});


			},
			recvMessage(msg) {
				var _this = this;
				if (msg.id != this.visitor_id) {
					this.showNoticeBar(msg.name + ":" + msg.content);
					return;
				}
				if(_this.messageExist["id_"+msg.msg_id]){
					return;
				}
				// if(msg.is_kefu == "yes"){
				// 	return;
				// }
				toolsHelper.playVoice();
				msg.mes_type = msg.is_kefu == "yes" ? "kefu" : "visitor";
				msg.content = _this.replaceContent(msg.content, _this.baseUrl);
				msg.avator=toolsHelper.getImageUrl(msg.avator,_this.baseUrl);
				this.messageExist["id_"+msg.msg_id]=1;
				this.messages.push(msg);
	
				_this.pageScrollToBottom();
				
				if(msg.mes_type=="visitor"){
					_this.inputingAction="";
				}
			},
			pageScrollToBottom: function(isFast) {
				var duration=300;
				if(isFast){
					duration=1;
				}
				this.$nextTick(() => {
					uni.pageScrollTo({
						scrollTop: 99999999999999999,
						duration:duration,
					})
				});
			},
			getFaces(){
				this.face=toolsHelper.emojiGifsMap(this.baseUrl);
			},
			placeFace() {
				var faces = [];
				for (var i = 0; i < this.faceTitles.length; i++) {
					faces[this.faceTitles[i]] = "/static/images/face/" + i + ".png";
				}
				return faces;
			},
			replaceContent(content, baseUrl) { // 转义聊天内容中的特殊字符
				if (typeof baseUrl == "undefined") {
					baseUrl = "";
				}
				var faces = this.placeFace();
				var _this=this;
				content=content.replace(/face\[([^\s\[\]]+?)\]/g, function (face) {  // 转义表情
				            var alt = face.replace(/^face/g, '');
				            return '<img width="28" class="faceiconImg" alt="' + alt + '" title="' + alt + '" src="'+baseUrl + faces[alt] + '">';
				        })
				        .replace(/img\[([^\s\[\]]+?)\]/g, function (face) {  // 转义图片
				            var src = face.replace(/^img\[/g, '').replace(/\]/g, '');
							var imgUrl=toolsHelper.getImageUrl(src,_this.baseUrl);
				            return '<img class="chatImagePic"  src="' +imgUrl + '?width=400"/>';
				        })
				        .replace(/audio\[([^\s\[\]]+?)\]/g, function (face) {  // 转义图片
				            var src = face.replace(/^audio\[/g, '').replace(/\]/g, '');
							var imgUrl=toolsHelper.getImageUrl(src,_this.baseUrl);
				            return '<audio controls ref="audio" src="'+imgUrl+'" id="audio"></audio>';
				        })
				        .replace(/file\[([^\s\[\]]+?)\]/g, function (face) {  // 转义图片
				            var src = face.replace(/^file\[/g, '').replace(/\]/g, '');
							var imgUrl=toolsHelper.getImageUrl(src,_this.baseUrl);
							var iconUrl=toolsHelper.getImageUrl('/static/images/download.png',_this.baseUrl);
				            return '<a href="'+imgUrl+'"><img src="'+iconUrl+'"/></a>';
				        })
				        .replace(/\[([^\]]+?)\]+link\[([^\]]+?)\]/g, function (face) {  // 转义超链接
				            var text = face.replace(/link\[.*?\]/g, '').replace(/\[|\]/g, '');
				            var src = face.replace(/^\[([^\s\[\]]+?)\]+link\[/g, '').replace(/\]/g, '');
				            return '<a href="'+src+'" target="_blank"/>'+text+'</a>';
				        })
						.replace(/product\[([^\[\]]+?)\]/g, function (product) {
							if(!arguments[1]){
								return;
							}
							var jsonStr=arguments[1].replace(/\'/g,'"');
							console.log(jsonStr);
							try{
								var info=JSON.parse(jsonStr);
								if(typeof info=="undefined"){
									return;
								}
								var title="";
								if(info.title){
									title=info.title;
								}
								var price="";
								if(info.price){
									var price=info.price;
								}
								var img="";
								if(info.img){
									img="<img src='"+toolsHelper.getImageUrl(info.img,_this.baseUrl)+"' style='width: 100px;height: 100px;margin-right: 15px;'/>";
								}
								var url="";
								if(info.url){
									url=info.url;
								}
								var html= `
									<a style='display: block;background: #fff;padding: 5px;border-radius: 2px;max-width: 98%;display: flex;border-radius: 5px;' href="`+url+`" target="_blank"/>
									`+img+`
				
									<div style='color: #333;'>
										<div>`+title+`</div>
										<div style='color: #ff7736;font-weight: bold;font-size: 16px;margin-top: 10px;'>`+price+`</div>
									</div>
									</a>
							`;
								return html;
							}catch (e) {
								return jsonStr;
							}
				
						});
				content=toolsHelper.replaceMutiFile(content,_this.baseUrl);
				return content;
			},
			//发送给客户
			chatToUser() {
				var _this = this;
				this.messageContent = this.messageContent.trim("\r\n");
				if (this.messageContent == "" || this.messageContent == "\r\n" || this.currentGuest == "") {
					uni.showModal({
						content: "内容不能为空"
					});
					return;
				}
				if (_this.isDisabled) {
					return
				}
				uni.showLoading({
					title: "发送中..."
				});
				_this.isDisabled = true;
				// var messages = _this.messages;
				// var msg = {};
				// msg.avator=toolsHelper.getImageUrl(this.kefuInfo.avator,_this.baseUrl);
				// msg.name=this.kefuInfo.nickname;
				// msg.content=_this.replaceContent(this.messageContent, _this.baseUrl);
				// msg.mes_type = "kefu";
				// msg.time=toolsHelper.getNowDate();
				// messages.push(msg);
				_this.pageScrollToBottom(true);
				uni.request({
					url: _this.baseUrl + '/kefu/message?token='+_this.token,
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					data: {
						to_id: _this.visitor_id,
						content: _this.messageContent,
						type: "kefu",
					},
					success: function(res) {
						_this.isDisabled = false,
							uni.hideLoading();
						var code = res.data.code;
						if (code != 200) {
							uni.showModal({
								content: res.data.msg
							});
						} else {
							_this.messageContent = "";
							// var messages = _this.messages;
							// var msg = res.data.result.data;
							// msg.mes_type = "kefu";
							// messages.push(msg);
							
						}
					}
				});
			},
			//关闭备注
			closeRemark(){
				this.remark=false;
				//this.$refs.remark.close();
			},
			//开启备注
			openRemark(){
				var _this=this;
				_this.remark=true;
				uni.request({
					url: this.baseUrl + '/kefu/visitor_attr?token='+_this.token,
					method: 'GET',
					data: {
						visitor_id: _this.visitor_id,
					},
					success: function(res) {
						var result=res.data.result;
						_this.realName=result.real_name;
						_this.tel=result.tel;
						_this.email=result.email;
						_this.qq=result.qq;
						_this.wechat=result.wechat;
						_this.comment=result.comment;
						console.log(res);
					}
				});
				_this.entTags=[];
				uni.request({
					url: this.baseUrl + '/kefu/tags?token='+_this.token,
					method: 'GET',
					success: function(res) {
						var result=res.data.result;
						for(var key in result){
							var item={
								"text":result[key].name,
								"value":result[key].name,
							}
							_this.entTags.push(item);
						}
					}
				});
				this.getTags();
				//this.$refs.remark.open();
			},
			//拉黑访客
			blackVisitor(blackType){
				var _this=this;
				var url=this.baseUrl 
				if(blackType=="visitor"){
					url=url+"/kefu/visitorBlack?token="+_this.token;
					uni.request({
						url: url,
						method: 'POST',
						data: {
							visitor_id: _this.visitor_id,
							name:_this.visitor_name,
						},
						success: function(res) {
							uni.showToast({
								title:res.data.msg,
								icon:"success",
							});
						}
					});
				}else{
					url=url+"/kefu/ipblack?token="+_this.token;
					uni.request({
						url: url,
						method: 'POST',
						header: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						data: {
							ip: _this.visitor_ip,
							name:_this.visitor_name,
						},
						success: function(res) {
							uni.showToast({
								title:res.data.msg,
								icon:"success",
							});
						}
					});
				}
			},
			//查询tags
			getTags(){
				var _this=this;
				uni.request({
					url: this.baseUrl + '/kefu/visitorTag?token='+_this.token,
					method: 'GET',
					data: {
						visitor_id: _this.visitor_id,
					},
					success: function(res) {
						var result=res.data.result;
						_this.visitorTags=result;
					}
				});
			},
			//关闭快速回复
			closeFastReply(){
				this.$refs.fastReply.close();
			},
			//开启快速回复
			openFastReply(){
				var _this=this;
				if(_this.replys.length!=0){
					_this.fastReplyBtn=true;
					return;
				}
				uni.showLoading({
					title: '加载中'
				});
				uni.request({
					url: this.baseUrl + '/replys?token='+_this.token,
					method: 'GET',
					success: function(res) {
						uni.hideLoading();
						var result=res.data.result;
						_this.replys=result;
						_this.fastReplyBtn=true;
					}
				});
			},
			saveRemark(){
				var _this=this;
				var info={
					visitor_id:this.visitor_id,
					visitor_attr:{
						real_name:this.realName,
						tel:this.tel,
						email:this.email,
						wechat:this.wechat,
						qq:this.qq,
						comment:this.comment,
					}
				}
				uni.request({
					url: _this.baseUrl + '/kefu/visitor_attrs?token='+_this.token,
					method: 'POST',
			
					data: info,
					success: function(res) {
						_this.$refs.remark.close();
					}
				});
				
			},
			//修改标签
			changeTag(e){
				var _this=this;
				 const value = e.detail.value[0].value;
				 console.log(value);
				this.doChangeTag(value);
			},
			doChangeTag(tagName){
				var _this=this;
				var info={
					visitor_id:this.visitor_id,
									tag_name:tagName
				}
				uni.request({
					url: _this.baseUrl + '/kefu/visitorTag?token='+_this.token,
					method: 'POST',
					data: info,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: function(res) {
						_this.getTags();
					}
				});
			},
			//删除标签
			delTag(tagName){
				var _this=this;
				var info={
					visitor_id:this.visitor_id,
					tag_name:tagName
				}
				uni.request({
					url: this.baseUrl + '/kefu/delVisitorTag?token='+_this.token,
					method: 'GET',
					data:info,
					success: function(res) {
						_this.getTags();
					}
				});
			},
			showNotice(msg) {
				// if (uni.getSystemInfoSync().platform == "android") {
				// 	if (window.plus) {
				// 		plus.push.createMessage(msg);
				// 	}
				// }
			},
			showNoticeBar(msg){
				var _this=this;
				_this.noticeContent=msg;
			},
			uploadImage(){
				var _this=this;
				uni.chooseImage({
				    success: (chooseImageRes) => {
				        const tempFilePaths = chooseImageRes.tempFilePaths;
				        uni.uploadFile({
				            url:  _this.baseUrl + '/uploadimg?token='+ _this.token,
				            filePath: tempFilePaths[0],
				            name: 'imgfile',
				            success: (res) => {
								console.log(res);
								var data=JSON.parse(res.data);
								if(data.code!=200){
									uni.showToast({
										title:data.msg,
										icon:"none",
									});
									return;
								}
								_this.messageContent+='img[' + data.result.path + ']';
								_this.chatToUser();
				            }
				        });
				    }
				});
			},
			uploadFile(){
				var _this=this;
	
				uni.chooseFile({
				    success: (path) => {
				        const tempFilePaths = path.tempFilePaths;
				        uni.uploadFile({
				            url:  _this.baseUrl + '/2/uploadFile?token='+ _this.token,
				            filePath: tempFilePaths[0],
				            name: 'realfile',
				            success: (res) => {
								console.log(res);

								var data=JSON.parse(res.data)
								if(data.code!=200){
									uni.showToast({
										title:data.msg,
										icon:"none",
									});
									return;
								}
								var info=JSON.stringify({
									name:data.result.name,
									ext:data.result.ext,
									size:data.result.size,
									path:data.result.path,
								})
								_this.messageContent='mutiFile[' + info+ ']';
								_this.chatToUser(true);
				            }
				        });
				    }
				});
			},
			//格式化时间
			formatTime(time) {
				var timeStamp = Math.round(new Date(time).getTime()/1000);
				var nowTime=Math.round(new Date().getTime()/1000);
				if((nowTime-timeStamp)<=3600*24){
					return toolsHelper.beautifyTime(timeStamp);
				}
				return time;
			},
			//长按事件
			longDelete(msgId) {
				var _this=this;
	　　　　　　uni.showModal({
	　　　　　　　　title: '撤回操作',
	　　　　　　　　content: '请问要撤回本条消息吗？',
	　　　　　　　　success:async function(res) {
	　　　　　　　　　　if (res.confirm) {
						var info={msg_id:msgId,visitor_id:_this.visitor_id}
						uni.request({
							url: _this.baseUrl + '/kefu/message_delete?token='+_this.token,
							method: 'POST',
							data:info,
							header: {
								'Content-Type': 'application/x-www-form-urlencoded'
							},
							success: function(res) {
								if(res.data.code!=200){
									uni.showToast({
										title:res.data.msg,
										icon:"error",
									});
									return;
								}
								for(var i=0;i<_this.messages.length;i++){
									if(_this.messages[i].msg_id==msgId){
										_this.messages.splice(i,1);
									}
								}
							}
						});
		　　　　　　　　} else if (res.cancel) {
		　　　　　　　　　　console.log('用户点击取消')
		　　　　　　　　}
	　　　　　　		}
				});
	
			},
			//表情点击事件
			faceIconClick:function(index){
				this.showFaceIcon=false;
				this.messageContent+="face"+this.face[index].name;
			},
			//长按事件
			trashMessage() {
				var _this=this;
	　　　　　　uni.showModal({
	　　　　　　　　title: '清空操作',
	　　　　　　　　content: '请问要清空所有消息吗？',
	　　　　　　　　success:async function(res) {
	　　　　　　　　　　if (res.confirm) {
						var info={visitor_id:_this.visitor_id}
						uni.request({
							url: _this.baseUrl + '/kefu/delVisitorMessage?token='+_this.token,
							method: 'GET',
							data:info,
							success: function(res) {
								_this.messages=[];
							}
						});
		　　　　　　　　}
	　　　　　　		}
				});
			},
			//客服转接
			transferKefu(){
				var _this=this;
				if(_this.otherKefuList.length!=0){
					_this.otherKefuBtn=true;
				}
				uni.request({
					url: _this.baseUrl + '/kefu/otherKefulist',
					method: 'get',
					header: {
						'token': _this.token
					},
					success: function(res) {
						var result=res.data.result;
						_this.otherKefuBtn=true;
						_this.otherKefuList=result;
					}
				});
			},
			//转移访客客服
			transKefuVisitor(kefu,visitorId){
				var _this=this;
				uni.request({
					url: _this.baseUrl + '/kefu/transKefu',
					data:{kefu_id:kefu,visitor_id:visitorId},
					method: 'get',
					header: {
						'token': _this.token
					},
					success: function(res) {
						_this.otherKefuBtn = false;
					}
				});
			},
			//翻译
			translate(index,content){
				var i=index;
				var _this=this;
				uni.request({
					url: _this.baseUrl + '/translate',
					data:{words:content,from:"auto",to:"zh"},
					method: 'get',
					header: {
						'token': _this.token
					},
					success: function(res,index) {
						var dst=res.data.result.dst;
						if(dst==""){
							return;
						}
						_this.messages[i].content=_this.messages[i].content+"<br/>"+dst
					}
				});
			},
			//翻译
			translateKefu(){
				var _this=this;
				var content=toolsHelper.replaceHtml(_this.messageContent);
				if(content==""){
					return;
				}
				uni.request({
					url: _this.baseUrl + '/translate',
					data:{words:content,from:"auto",to:"en"},
					method: 'get',
					header: {
						'token': _this.token
					},
					success: function(res,index) {
						var dst=res.data.result.dst;
						if(dst==""){
							return;
						}
						_this.messageContent=dst;
					}
				});
			},
			confirm(voicePath){
				var _this=this;
				this.showRecorder=false;
				uni.uploadFile({
				    url:  _this.baseUrl + '/uploadaudio?token='+ _this.token,
				    filePath: voicePath,
				    name: 'realfile',
				    success: (res) => {
						var data=JSON.parse(res.data)
						_this.messageContent+='audio[/' + data.result.path + ']';
						_this.chatToUser();
						
				    }
				});
			},
			openRecord() {
				this.$refs.recorderDialog.open();
			},
			startRecord() {
				uni.showToast({
				  title: '开始录音，如需结束请点击停止录音',
				  duration: 5000, // 提示框停留时间，默认为 1500 毫秒
				  icon: 'none' // 提示框图标，可选值为 success / loading / none，默认为 none
				});
				this.endRecorderBtn=true;
				this.sendRecorderBtn=false;
				this.$refs.recorder.start()
			},
			endRecord() {
				uni.showToast({
				  title: '录音已经结束',
				  duration: 2000, // 提示框停留时间，默认为 1500 毫秒
				  icon: 'none' // 提示框图标，可选值为 success / loading / none，默认为 none
				});
				this.endRecorderBtn=false;
				this.sendRecorderBtn=true;
				this.$refs.recorder.stop();
			},
			sendRecord() {
				var _this=this;
				if(!this.recorder || !this.recorder.localUrl){
					uni.showToast({
					  title: '录音失败',
					  duration: 2000, // 提示框停留时间，默认为 1500 毫秒
					  icon: 'none' // 提示框图标，可选值为 success / loading / none，默认为 none
					});
					return;
				}
				console.log('上传录音');
				
				uni.uploadFile({
				    url:  this.baseUrl + '/2/uploadAudio?token='+ this.token,
				    filePath: this.recorder.localUrl,
				    name: 'realfile',
				    success: (res) => {
						var data=JSON.parse(res.data)
						_this.messageContent+='audio[' + data.result.path + ']';
						_this.chatToUser();
						_this.recorderBtn=false;
						_this.endRecorderBtn=true;
						_this.sendRecorderBtn=false;
						
				    }
				});
			},
            handlerRecordSuccess(res) {
                console.log(res)
                this.recorder = res
            },
			handlerRecordError(res) {
				uni.showToast({
				  title: res,
				  duration: 3000,
				  icon: 'none'
				});
			},
			//初始化peerjs
			initPeerjs:function(visitorId){
				var _this=this;
				var peer = new Peer();
				peer.on('open', function(id) {
					console.log('My peer ID is: ' + id);
					uni.request({
						url: _this.baseUrl + '/kefu/callVisitor?token='+_this.token,
						method: 'POST',
						data: {
							peer_id:id,
							visitor_id:visitorId,
							action:"accept"
						}
					});
					_this.peerjs.peerjsId=id;
					_this.peerjs.visitorId=visitorId;
				});
				peer.on('close', function() {
					_this.callClear();
				});
				peer.on('disconnected', function() {
					_this.callClear();
				});
				peer.on('error', function() {
					_this.callClear();
				});
				peer.on('call', function(call) {
					console.log('peer call',call);
					_this.peerjs.call=call;
					uni.showModal({
						title: '请选择语音/视频接待',
						cancelText: "语音",
						confirmText: "视频", 
						showCancel: true, // 是否显示取消按钮，默认为 true
						success: (res) => {
							if(res.confirm) {  
								_this.startUserMedia(visitorId,true);
							} else {  
								_this.startUserMedia(visitorId,false);
							} 
						}
					})
				});
				this.peerjs.peer=peer;
			},
			//开始流
			startUserMedia(visitorId,isVideo){
				var _this=this;
				if(!_this.peerjs.call) return;
				let res=toolsHelper.getCompatibleUserMedia({video:isVideo, audio: {
					noiseSuppression: true,
					echoCancellation: true,
				}},function(localStream) {
					_this.peerjs.localStream=localStream;
					_this.peerjs.call.answer(localStream);
					_this.peerjs.call.on('stream', function(remoteStream) {
						var videoTracks = remoteStream.getVideoTracks();
						var audioTracks = remoteStream.getAudioTracks();

						if (videoTracks.length > 0) {
							_this.peerjs.remoteVideoStream=remoteStream;
							var remoteVideo = document.getElementsByTagName('video')[0];
							remoteVideo.srcObject = remoteStream;
							remoteVideo.play();
						}else if (audioTracks.length > 0) {
							_this.peerjs.remoteAudioStream=remoteStream;
							var remoteAudia = document.getElementsByTagName('audio')[0];
							remoteAudia.srcObject = remoteStream;
							remoteAudia.play();
						}

					});
					_this.peerjs.call.on('close', function() {
						_this.callClear();
					});
					_this.peerjs.call.on('error', function(err) {
						_this.callClear();
					});
				},function(err) {
					console.log(err);
					uni.showToast({
					  title: err.toString(),
					  duration: 5000,
					  icon: 'none'
					});
					_this.callClear();
				});
				if(!res){
					uni.showToast({
					  title: "Your browser does not support the getUserMedia API.",
					  duration: 5000,
					  icon: 'none'
					});
					_this.callClear();
				}
			},
			//挂断
			refuseCall(){
				var _this=this;
				if(_this.peerjs.visitorId){
					uni.request({
						url: _this.baseUrl + '/kefu/callVisitor?token='+_this.token,
						method: 'POST',
						data: {
							peer_id:"222",
							visitor_id:_this.peerjs.visitorId,
							action:"refuse"
						}
					});
					_this.peerjs.visitorId="";
				}
			},
			//打电话
            callPhone:function(){
                var _this=this;
				uni.request({
					url: _this.baseUrl + '/kefu/callVisitor?token='+_this.token,
					method: 'POST',
					data: {
						peer_id:"222",
						visitor_id:_this.visitor_id,
						action:"callPhone"
					},
					success: (res) => {
						uni.showToast({
						  title: '请求语音通话指令发出',
						  duration: 5000, // 提示框停留时间，默认为 1500 毫秒
						  icon: 'none' // 提示框图标，可选值为 success / loading / none，默认为 none
						});
					}
				});

            },
            //打视频
            callVideo:function(){
                var _this=this;
				uni.request({
					url: _this.baseUrl + '/kefu/callVisitor?token='+_this.token,
					method: 'POST',
					data: {
						peer_id:"222",
						visitor_id:_this.visitor_id,
						action:"callVideo"
					},
					success: (res) => {
						uni.showToast({
						  title: '请求视频通话指令发出',
						  duration: 5000, // 提示框停留时间，默认为 1500 毫秒
						  icon: 'none' // 提示框图标，可选值为 success / loading / none，默认为 none
						});
					}
				});

            },
			//清理call
			callClear(){
				var _this=this;
				if(_this.peerjs.call){
					_this.peerjs.call.close();
					_this.peerjs.call=null;
				} 
				if(_this.peerjs.remoteVideoStream){
					var tracks=_this.peerjs.remoteVideoStream.getTracks();
					for(var i=0;i<tracks.length;i++){
						tracks[i].stop();
					}
					_this.peerjs.remoteVideoStream=null;
				}
				if(_this.peerjs.remoteAudioStream){
					var tracks=_this.peerjs.remoteAudioStream.getTracks();
					for(var i=0;i<tracks.length;i++){
						tracks[i].stop();
					}
					_this.peerjs.remoteAudioStream=null;
				}
				if(_this.peerjs.localStream){
					var tracks=_this.peerjs.localStream.getTracks();
					for(var i=0;i<tracks.length;i++){
						tracks[i].stop();
					}
					_this.peerjs.localStream=null;
				}
				this.refuseCall();
			},
			//搜索快捷回复
			searchReply(){
				let _this=this;
				console.log(this.searchReplyItem);
				let item=this.searchReplyItem;
				if(item=="") return;
				uni.request({
					url: this.baseUrl + '/kefu/replySearch?token='+_this.token,
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					data: {
						search:item,
					},
					success: (res) => {
						var result=res.data.result;
						if(result.length<=0) return;
						_this.replys=result;
					}
				});
			},
			//跳转
			goTo(url){
				uni.reLaunch({
				  url:url
				});
			},
			//发送评价
			sendComment(){
				let _this=this;
				uni.request({
					url: this.baseUrl + '/kefu/sendComment?token='+_this.token,
					method: 'GET',
					data: {
						visitor_id:this.visitor_id,
					},
					success: (res) => {
						uni.showToast({
							title:"发送评价请求成功",
							icon:"none",
						});
					}
				});
			},
			//切换机器人
			switchRobotStatus(e){
				let _this=this;
				let value=e.detail.value ? "1" : "2";
				uni.request({
					url: this.baseUrl + '/kefu/visitorState',
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded',
						'token':_this.token,
					},
					data: {
						state:this.visitor.state,
						position:1,
						value:value,
						visitor_id:this.visitor_id,
					},
					success: (res) => {
						_this.getVisitor();
						uni.showToast({
							title:"切换机器人状态成功",
							icon:"none",
						});
					}
				});
			},
}
	}
</script>

<style>
	page {
	   background-color: #eef0f6;
	}
	.flyAvatar {
		display: inline-block;
		box-sizing: border-box;
		text-align: center;
		color: #fff;
		background: #C0C4CC;
		width: 40px;
		height: 40px;
		line-height: 40px;
		border-radius: 50%;
		margin-top: 5px;
	}
	.chatContent .chatImagePic{
		max-width: 100%!important;
		display: inline-block;
	}
	.chatUser {
		line-height: 24px;
		font-size: 12px;
		white-space: nowrap;
		color: #999;
		text-align: left;
	}

	.chatLittle {
		width: 12.5%;
		float: left;
	}

	.chatBig {
		width: 87.5%;
		float: right;
	}

	.chatBox {
		padding: 0 4px;
	}
	.chatContent a{
		text-decoration: none;
	}
	.chatBoxMe .chatContent {
		float: right;
		background-color: rgb(201,231,255);
	}

	.chatBoxMe .chatContent:after {
		border-top-color: rgb(152, 225, 101);
	}

	.chatBoxMe .chatLittle {
		width: 12.5%;
		float: right;
		text-align: right;
	}

	.chatBoxMe .chatUser {
		text-align: right
	}

	.chatBoxMe .chatContent:after {
		left: auto;
		right: -10px;
	}

	.chatContent {
		background-color: rgb(255,255,255);
		color: #000;
		border: 1px solid rgb(242, 242, 242);
		padding: 5px 7px;
		word-break: break-all;
		position: relative;
		border-radius: 5px;
		display: inline-block;
		margin: 0px 4px;
		font-size: 13px;
		line-height: 23px;
	}

	.chatBoxMe .chatContent {
		margin-right: 4px;
	}

	.chatTime {
		text-align: center;
		color: #bbb;
		margin: 5px 0;
		font-size: 12px;
	}

	.chatArea {
		width: 100%;
		height: 70px;
		padding: 2px 5px;
		background: #fff;
		font-size: 13px;
		line-height: 24px;
	}

	.btnArea {
		position: absolute;
		right: 5px;
		bottom: 10px;
		z-index: 2;
		background: linear-gradient(90deg, #3875EA 0%, #1890FC 100%);
	}
	.btnArea uni-button{
		width: 55px;
		height: 40px;
		line-height: 40px;
		text-align: center;
		font-size: 13px;
	}
	.chatBoxSendIcons{
/* 		position: absolute;
		left: 2px;
		bottom: 2px; */
	}
	.chatBoxSendIcons .mr-10{
		margin: 0px 5px 0px 10px
	}
	.visitorFaceBox {
		position: absolute;
		bottom: 70px;
	}

	.chatBoxSend {
		background: #fff;
		height: 140px;
		position: fixed;
		bottom: 0px;
		left: 0px;
		width: 100%;
		border-top: 1px solid #e4e4e4;
		padding-top: 5px;
	}

	.chatContext {
		text-align: left;
		position: relative;
		padding: 10px;
		padding-bottom: 150px;
		padding-top: 10px;
	}
	.visitorNotice{
		position: fixed;
		z-index: 9;
	}
	.visitorNotice .uni-table{
		background-color: #f5f5f5;
	}
	.visitorNotice .uni-table-td{
		margin-top: 10px;
		font-size: 12px;
		color: #6c6c6c;
		padding: 5px 10px;
	}
	.inputing{
		padding: 2px 4px;
		color: #6c6c6c;
		font-size: 12px;
		position: absolute;
		top: -20px;
	}
	.folderBtn {
	    display: inline-block;
	    background-color: transparent;
	    overflow: hidden;
	    font-size: 1px;
	}
	.folderBtn:before {
	    content: '';
	    float: left;
	    background-color: #9da0a0;
	    width: 15px;
	    height: 3px;
	    margin-left: 2px;
	    border-top-left-radius: 2px;
	    border-top-right-radius: 2px;
	    box-shadow: 2px 2px 0 0 #9da0a0;
	}
	.folderBtn:after {
	    content: '';
	    float: left;
	    clear: left;
	    background-color: #d4d6d6;
	    width: 33px;
	    height: 22px;
	    border-radius: 1px;
	}
	.remarkDialog{
		padding: 10px;
	}
	.replyDialog{
		max-width: 100%;
		height: 500px;
	}
	.overflowYauto{
		overflow-y: auto;
	}
	.replyTitle{
		color: #333;
		font-size: 14px;
		background: #e3e3e3;
		padding: 5px 7px;
	}
	.replyContent{
		padding: 20px;
	}
	.replyBox{
		margin: 10px 15px;
		line-height: 22px;
		border: 1px solid #e6e6e6;

	}
	.clear {
		clear: both;
	}
	.area{
		border: 1px solid #c8c7cc;
		padding: 2px;
	}
	.chatReadStatus {
		font-size: 12px;
		color: #7f7f7f;
		margin: 8px 5px 0px 0px;
		float: right;
	}
	.deleteMessage{
		font-size: 12px;
		color: rgb(0 167 255);
		margin: 8px 5px 0px 0px;
		float: right;
	}
	.faceBox {
	    width: 100%;
	    background: #fff;
	    z-index: 99999999;
		position: absolute;
		bottom: 145px;
	}
	.faceBoxList .faceIcon{
	    cursor: pointer;
	    float: left;
	    border: 1px solid #e8e8e8;
	    width: 28px;
	    overflow: hidden;
	    margin: -1px 0 0 -1px;
	    padding: 4px 2px;
	    text-align: center;
	}
	.chatContext .faceiconImg{
		width: 28px!important;
		height: 28px!important;
	}
	.topBtns{
		display: flex;
		flex-direction: row;
		align-items: center;
	}
	.topBtns .txtBtn{
		line-height: 2;
		font-size: 12px;
		padding: 0 0.8em;
		margin: 0 5px 0 4px;
	}
	.fastReplyBox{
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 999;
		height: 100%;
		background: #fff;
		overflow: auto;
	}
	.recorderBox{
		padding: 10px;
		display: flex;
		flex-direction: column;
	}
	.recorderBtn{
		margin: 10px 20px;
	}
	.remoteVideoMask{
		width: 100%;
		height: 100%;
		position: fixed;
		z-index: 9999999;
		left: 0px;
		top: 0px;
		background: #333;
	}
	.remoteVideoMaskLogo{
	    width: 60px;
	    height: 60px;
	    position: absolute;
	    border-radius: 5px;
	    z-index: 9;
	    top: 60px;
	    left: 50%;
	    transform: translateX(-50%);
	}
	.refuse{
		bottom: 60px;
		position: fixed;
		left: 50%;
		transform: translateX(-50%);
		display: inline-block;
		width: 60px;
		height: 60px;
		color: #fff;
		background-color: #f56c6c;
		border-color: #f56c6c;
		text-align: center;
		line-height: 60px;
		border-radius: 50%;
	}
	.emojis{
		background-color: #fff;
		display: flex;
		flex-wrap: wrap;
		height: 160px;
		overflow: auto;
		font-size: 20px;
	}
	.emojis span{
		display: block;
		margin: 5px;
		cursor: pointer;
	}
</style>
